import {defineStore} from "pinia";
import {computed, ref} from "vue";
import {useOrgStore} from "@/store/modules/organization";
import {ProductList} from "@/services/api/product/index.ts";

export const useProductStore = defineStore('product',()=>{
    const dataSource = ref<ProductListType[]>([])
    const loading = ref<boolean>(false)
    const searchTerm = ref<string>('')
    const orgStore = useOrgStore()
    const data = computed(()=>{
        const term = searchTerm.value.trim().toLowerCase()
        if (!term) return dataSource.value
        return dataSource.value.filter(item=>item.name.toLowerCase().includes(term))
    })
    const fetchList = async (force?:boolean)=>{
        if(!force && dataSource.value.length > 0){
             return
        }
        try {
            loading.value = true
            const res = await ProductList(orgStore.id)
            if (res.code === 200){
                dataSource.value = res.data
            }
        }catch{}
        finally {
            setTimeout(()=>loading.value = false,100)
        }
    }
    const create = async (form:ProductFormType)=>{
        console.log(form);
    }
    const update = async (form:ProductFormType)=>{
        console.log(form);
    }
    const remove = async (id:number)=>{
        console.log(id);
    }
    return {
        dataSource,
        fetchList,
        create,
        update,
        remove,
        data,
        searchTerm,
        loading
    }
},{persist:{pick:['dataSource']}})